package com.tj.admin.rest.admin;

import com.fqgj.common.utils.MD5;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.tj.admin.auth.anno.VisitorAccessible;
import com.tj.admin.auth.domain.Admin;
import com.tj.admin.auth.service.AdminService;
import com.tj.bo.common.conf.api.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * User: binary (mr.vencnet@gmail.com)
 * Date: 2020-08-11
 * Time: 10:48
 */
@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/login")
    @VisitorAccessible
    public ApiResponse<String> login(@RequestBody LoginRequest request) {

        if (StringUtils.isEmpty(request.getAccount()) || StringUtils.isEmpty(request.getPassword())) {
            throw new ApplicationException("账号或密码异常");
        }

        Admin oneAdminByAccount = adminService.getOneAdminByAccount(request.getAccount());
        if (oneAdminByAccount == null) {
            throw new ApplicationException("账号或密码错误");
        }

        if (!oneAdminByAccount.getPassword().equals(MD5.md5(request.getPassword()))) {
            throw new ApplicationException("账号或密码有误");
        }

        //生成新的token
        String newToken = MD5.md5(System.currentTimeMillis() + request.getAccount());
        adminService.addNewAccessToken(oneAdminByAccount.getId().intValue(), newToken);
        return new ApiResponse<>(newToken);


    }

    public static void main(String[] args) {
        String abc = MD5.md5("123456");
        System.err.println(abc);
    }
}
